package com.wolan.rpc.testProxy;

import com.wolan.rpc.server.HelloService;
import com.wolan.rpc.server.HelloServiceImpl;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.net.URL;

/**
 * Created by fei.chen on 2016/3/28.
 */
public class testProxy {
    public static <T> T proxy(final Class<T> interfaceClass) {
        return (T) Proxy.newProxyInstance(interfaceClass.getClassLoader(), new Class<?>[]{interfaceClass}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                Object result = method.invoke(new HelloServiceImpl(), args);//通过反射机制获得类的方法，并调用这个方法
                System.out.println("method.getName() = " + method.getName() + "method.getParameterTypes() = " + method.getParameterTypes());
                //3中获取Class类信息方式
                System.out.println(new HelloServiceImpl().getClass().getMethod(method.getName(), method.getParameterTypes()).invoke(new HelloServiceImpl(), args));
                System.out.println(HelloService.class.getMethod(method.getName(), method.getParameterTypes()).invoke(new HelloServiceImpl(), args));
                System.out.println(Class.forName("com.wolan.rpc.server.HelloService").getMethod(method.getName(), method.getParameterTypes()).invoke(new HelloServiceImpl(), args));

                return result;
            }

        });
    }

    public static void main(String[] args) {
        HelloService service = proxy(HelloService.class);
        System.out.println(service.hello("hello"));
        System.out.println(service.getClass().getName());

        URL[] urls = sun.misc.Launcher.getBootstrapClassPath().getURLs();
        for (int i = 0; i < urls.length; i++) {
            System.out.println(urls[i].toExternalForm());
        }

        System.out.println(System.getProperty("java.ext.dirs"));
        ClassLoader extensionClassloader=ClassLoader.getSystemClassLoader().getParent();
        System.out.println("the parent of extension classloader : "+extensionClassloader.getParent());

        System.out.println(System.getProperty("java.class.path"));

        System.out.println(System.class.getClassLoader());

    }
}
